//
//  AVPlayerViewController.m
//  NewMusic
//
//  Created by dllo on 15/11/18.
//  Copyright © 2015年 Going. All rights reserved.
//

#import "AVPlayerViewController.h"
#import "AVFootView.h"
#import <AVFoundation/AVFoundation.h>
#import "SliderVoiceView.h"
#import "AVPlayerHeaderView.h"
#import "CustomerNetworking.h"
#import "TheNewMVModel.h"
#import <SDWebImageManager.h>
#import <UIImageView+WebCache.h>
#import "MvListModel.h"
#import "PlayerViewController.h"
@interface AVPlayerViewController () <UITableViewDataSource, UITableViewDelegate, HQAVplayerChangeStatus>
// 播放器控件
@property (nonatomic, retain) AVPlayer *player;
// 播放器底层View
@property (nonatomic, retain) UIView *AVBackView;
// 播放底部轻拍视图
@property (nonatomic, retain) AVFootView *AVFootView;
// tableView不解释
@property (nonatomic, retain) UITableView *tableView;
// 定时器(下半视图)
@property (nonatomic, retain) NSTimer *Viewtimer;
// 放置播放器控件
@property (nonatomic, retain) AVPlayerLayer *playLayer;
// 判断当前屏幕状态
@property (nonatomic, assign) BOOL screenState;
// 记录当前位置
@property (nonatomic, assign) CGFloat startPoint;
// 关联当前音量控制器
@property (nonatomic, retain) SliderVoiceView *sliderVoiceView;
//数组数组
@property (nonatomic, retain) NSMutableArray *dataArray;
// 获取进度条监听
@property (nonatomic, assign) id progressView;
@end

@implementation AVPlayerViewController

- (void)dealloc
{
    [_player release];
    [_AVBackView release];
    [_AVFootView release];
    [_tableView release];
    [_Viewtimer release];
    [_playLayer release];
    [_urlString release];
    [_dataArray release];
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.screenState = NO;
    self.dataArray = [NSMutableArray array];
    // 创建navgation
    [self creatNav];
    // 创建播放界面 , 音量界面
    [self creatPlayer];
    // 创建tableView
    [self creatTableView];
    //获取数据
    [self loadData];
}
#pragma 监听缓存
- (void)addObseverToPlayer:(AVPlayerItem *)playerItem
{
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}
#pragma 缓存监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    AVPlayerItem *currentItem = object;
    if ([keyPath isEqual:@"loadedTimeRanges"])
    {
        NSArray *array = currentItem.loadedTimeRanges;
        CMTimeRange timeRange = [[array lastObject] CMTimeRangeValue];
        [self.AVFootView.progress setProgress:(CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration)) / CMTimeGetSeconds(currentItem.duration) animated:YES];
    }
}
#pragma 播放与停止按钮(协议)
- (void)changeAVStatusWith:(NSInteger)num
{
    self.Viewtimer = nil;
    [self.Viewtimer invalidate];
    if (0 == num) {
        [self.player play];
    } else {
        [self.player pause];
    }
    self.Viewtimer = [NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(ViewChange) userInfo:nil repeats:NO];
}
#pragma 进度条(协议)
- (void)changeAvSlider:(CGFloat)num
{
    self.Viewtimer = nil;
    [self.Viewtimer invalidate];
    CMTime changeTime = CMTimeMakeWithSeconds(num, 1);
    [self.player seekToTime:changeTime completionHandler:^(BOOL finished) {
        [self.player play];
        self.AVFootView.startButton.selected = NO;
    }];
    self.Viewtimer = [NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(ViewChange) userInfo:nil repeats:NO];
}
#pragma 全屏协议方法
- (void)setFullScreen
{
    if (!self.screenState)
    {
        [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        self.tableView.frame = CGRectMake(375, 210, 375, 457);
        [UIView animateWithDuration:.5f animations:^{
            self.AVBackView.frame = CGRectMake(0, 146, 667, 375);
            [self.AVBackView setTransform:CGAffineTransformMakeRotation(M_PI / 2)];
            self.playLayer.frame =  CGRectMake(0, 146, 667, 375);
            self.AVFootView.frame = CGRectMake(146, 145, 375, 30);
        }];
        self.screenState = YES;
    } else {
        self.screenState = NO;
        [UIView animateWithDuration:.5f animations:^{
            self.AVBackView.frame = CGRectMake(82.5, -82.5, 210, 375);
            self.AVBackView.transform = CGAffineTransformMakeRotation(!M_PI / 2);
            self.playLayer.frame =  self.AVBackView.frame;
            self.AVFootView.frame = CGRectMake(0, 180, 30, 375);
        } completion:^(BOOL finished) {
            [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
            self.tableView.frame = CGRectMake(0, 210, 375, 457);
        }];
    }
}
#pragma 监听进度条
- (void)creatSliderView
{
    // 自带监听方法
    _progressView = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        NSInteger currentTime = (NSInteger)CMTimeGetSeconds(time);
        NSInteger totalTime = (NSInteger)CMTimeGetSeconds(self.player.currentItem.duration);
        if (self.player.currentItem)// 时长信息存储
        {
            self.AVFootView.leftLabel.text = [NSString stringWithFormat:@"%.2ld:%.2ld", currentTime / 60 , currentTime % 60];
            self.AVFootView.rightLabel.text = [NSString stringWithFormat:@"%.2ld:%.2ld", totalTime / 60, totalTime % 60];
            self.AVFootView.slider.maximumValue = totalTime;
            self.AVFootView.slider.value = currentTime;
        }
    }];
}
#pragma 页面出现
- (void)tapAction
{
    if (!self.screenState)
    {
        self.Viewtimer = nil;
        [self.Viewtimer invalidate];
        if (self.AVFootView.frame.origin.y > 180)
        {
            [UIView animateWithDuration:0.5 animations:^{
                self.AVFootView.frame = CGRectMake(0, 180, 375, 30);
            }];
            self.Viewtimer = [NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(ViewChange) userInfo:nil repeats:NO];
        } else {
            [UIView animateWithDuration:0.5 animations:^{
                self.AVFootView.frame = CGRectMake(0, 210, 375, 30);
            }];
        }
    }
}
- (void)ViewChange
{
    if (!self.screenState)
    {
        [UIView animateWithDuration:0.5 animations:^{
            self.AVFootView.frame = CGRectMake(0, 210, 375, 30);
        }];
    }
}
#pragma 赋值增加监听
- (void)creatPlayer
{
    self.AVBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375, 210)];
    [self.view addSubview:self.AVBackView];
    [_AVBackView release];
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:self.urlString]];
    self.player = [AVPlayer playerWithPlayerItem:item];
    [item release];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    CGFloat volNum = [user floatForKey:@"voice"];
    self.player.volume = volNum;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PlayerFinish) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    self.playLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playLayer.frame = self.AVBackView.frame;
    self.playLayer.backgroundColor = [UIColor blackColor].CGColor;
    [self.AVBackView.layer addSublayer:self.playLayer];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.AVBackView addGestureRecognizer:tap];
    [tap release];
    self.AVFootView = nil;
    if (self.AVFootView== nil) {
        self.AVFootView = [[AVFootView alloc] initWithFrame:CGRectMake(0, 210, 375, 30)];
    }
    self.AVFootView.delegate = self;
    [self.AVBackView addSubview:self.AVFootView];
    [_AVFootView release];
    [self.player play];
    // 监听进度条
    [self creatSliderView];
    // 监听缓存条和总时间
    [self addObseverToPlayer:self.player.currentItem];
    [_player release];
    
}
#pragma mark 获取数据
- (void)loadData {
  [CustomerNetworking customerConnectWithURL:[NSString stringWithFormat:@"http://api.dongting.com/sim/mv/%@/similarity?app=ttpod&v=v8.1.1.2015110616",  self.idString] andParameters:nil andBlock:^(id response) {
      NSArray *array = [response valueForKey:@"data"];
      if (![array isKindOfClass:[NSNull class]]) {
          for (NSDictionary *dic in array) {
              TheNewMVModel *model = [[TheNewMVModel alloc]initWithDictionary:dic];
              [self.dataArray addObject:model];
              [model release];
          }
      }
      [self.tableView reloadData];
    }];
}
#pragma 创建tableView
- (void)creatTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 210, 375, 457) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor colorWithRed:0.145 green:0.216 blue:0.255 alpha:1.000];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //头视图
    AVPlayerHeaderView *headerView = [[AVPlayerHeaderView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    self.tableView.tableHeaderView = headerView;
    [self.view addSubview:self.tableView];
    [_tableView release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cellIdentify";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentify]autorelease];
    }
    cell.detailTextLabel.textColor = [UIColor whiteColor];
    cell.textLabel.textColor = [UIColor whiteColor];
    if (_dataArray.count != 0) {
        cell.detailTextLabel.text = [[_dataArray objectAtIndex:indexPath.row] singerName];
        cell.textLabel.text = [[_dataArray objectAtIndex:indexPath.row] videoName];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataArray.count != 0) {
        [self.player pause];
        [self removeNotion];
        [self removeObserverFromPlayerItem:self.player.currentItem];
        [self removeObjectFromProgressView];
        NSString *str = [[self.dataArray[indexPath.row] mvList].lastObject urlStr];
        AVPlayerItem *item = [self getPlayerItemWithIndex:str];
        [self.player replaceCurrentItemWithPlayerItem:item];
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PlayerFinish) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        // 监听进度条
        [self creatSliderView];
        // 监听缓存条和总时间
        [self addObseverToPlayer:self.player.currentItem];
        NSString *videoid = [[self.dataArray[indexPath.row] mvList].lastObject videoId];
        self.idString = videoid;
        [self.dataArray removeAllObjects];
        [self loadData];
        [self.player play];
    }
}
- (void)removeObjectFromProgressView
{
    [_player removeTimeObserver:_progressView];
}
- (AVPlayerItem *)getPlayerItemWithIndex:(NSString *)url
{
    AVPlayerItem *playItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:url]];
    return playItem;
}
- (void)removeNotion
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem
{
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}
#pragma 结束执行
- (void)PlayerFinish
{
    [self.AVFootView.slider setValue:0 animated:YES];
    self.AVFootView.startButton.selected = YES;
    [self.player seekToTime:kCMTimeZero];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (1 == event.allTouches.count)
    {
        if (!self.screenState)
        {
            self.startPoint = [[touches anyObject] locationInView:self.view].y;
        } else {
            self.startPoint = [[touches anyObject] locationInView:self.view].x;
        }
    }
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (1 == event.allTouches.count)
    {
        CGFloat y = 0;
        CGFloat temp = 0;
        if (!self.screenState)
        {
            y = [[touches anyObject] locationInView:self.view].y;
            temp = y - self.startPoint;
        } else {
            y = [[touches anyObject] locationInView:self.view].x;
            temp = self.startPoint - y;
        }
        NSInteger value = (NSInteger)temp;
        if (self.player.volume + (-value / 15) >= 15)
        {
            self.player.volume = 15;
        } else if (self.player.volume + (-value / 15) < 0) {
            self.player.volume = 0;
        } else {
            self.player.volume += -value / 15;
        }
        NSLog(@"%f", self.player.volume);
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setFloat:self.player.volume forKey:@"voice"];
    }
}
- (void)creatNav
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-xia"] style:UIBarButtonItemStylePlain target:self action:@selector(barLeft)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:200 / 255.0 green:200 / 255.0 blue:200 / 255.0 alpha:1.0];
    [[self findHairlineImageViewUnder:self.navigationController.navigationBar] setHidden:YES];
}
- (void)barLeft
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.player pause];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"statePlayer" object:self userInfo:nil];
      [[NSNotificationCenter defaultCenter] postNotificationName:@"changeControlView" object:self userInfo:nil];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[PlayerViewController sharePlayerViewController] stopMusic];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
